package com.upc.feedish.utils;

import android.graphics.Bitmap;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;




public class MyTools {

    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "XVMqBHRYoGxWNzppMgGBKCUX";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "V1DAEdZYDIFjDImaTqUr7xWB5GdryTvy";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

    public static String bitmapToBase64(Bitmap bitmap) {      //照片编码
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
        try {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }
    public static StringBuffer getRequestData1(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
        try {
            stringBuffer.append("{");
            for(Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append("\""+entry.getKey()+"\"")
                        .append(":")
                        .append("\""+URLEncoder.encode(entry.getValue(), encode)+"\"")
                        .append(",");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
            stringBuffer.append("}");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }
    public static String submitPostData(String strUrlPath,Map<String, String> params, String encode) {
//        System.out.println(getRequestData1(params,encode).toString());
        byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体
        //String s="image=aaa&id_card_side=front";
        //data=s.getBytes();
        try {
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);     //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));//设置请求体的长度
            OutputStream outputStream = httpURLConnection.getOutputStream();//获得输出流
            outputStream.write(data);                                       //向服务器写入数据
            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            if(response == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = httpURLConnection.getInputStream();
                return dealResponseResult(inputStream);                     //处理服务器的响应结果
            }
        } catch (IOException e) {
//e.printStackTrace();
            return "err: " + e.getMessage().toString();
        }
        return "-1";
    }
    public static String dealResponseResult(InputStream inputStream) {
        String resultData = null;      //存储处理结果
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultData = new String(byteArrayOutputStream.toByteArray());
        return resultData;
    }

//    public static class Sample {
//        //设置APPID/AK/SK
//        public static final String APP_ID = "App ID";
//        public static final String API_KEY = "Api Key";
//        public static final String SECRET_KEY = "Secret Key";
//
//        public static void main(String[] args) {
//            // 初始化一个AipImageClassify
//            AipImageClassify client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);
//
//            // 可选：设置网络连接参数
//            client.setConnectionTimeoutInMillis(2000);
//            client.setSocketTimeoutInMillis(60000);
//
//
//
//            // 调用接口
//            String path = "test.jpg";
//            JSONObject res = client.objectDetect(path, new HashMap<String, String>());
//            System.out.println(res.toString());
//
//        }
//    }
//    public void sample(AipImageClassify client) {
//        // 传入可选参数调用接口
//        HashMap<String, String> options = new HashMap<String, String>();
//        options.put("top_num", "3");
//
//
//
//        // 参数为本地路径
//        String image = "test.jpg";
//        JSONObject res = client.animalDetect(image, options);
//        System.out.println(res.toString());
//
//        // 参数为二进制数组
//        byte[] file = r("test.jpg");
//        res = client.animalDetect(file, options);
//        System.out.println(res.toString());
//    }
//
//
}
